#!/bin/bash

# This script knocks on the firewall configured by
# knocksystem.sh with the right sequence (given the
# right value of environmentvariable KNOCKSEED).
# After running this script there is a window of 30 seconds to connect.
# See also the comments in in knocksystem.sh.

IP=xxx.xxx.xxx.xxx  # <- replace by IP of your server

# validate KNOCKSEED
re='^[+-]?[0-9]+([.][0-9]+)?$'
if ! [[ $KNOCKSEED =~ $re ]] ; then
   echo KNOCKSEED must hold a numeric value. Exit 1. >&2 ; exit 1
fi

# calculate md5sum
dd=`date +"%Y%m%d%H00"`
d5=`echo $((dd+KNOCKSEED)) | md5sum`

# knock on three ports
for i in 1 2 3 ; do

   s=$((1+5*(i-1)))                                   # start positions 1, 6 and 11

   gate=`echo $d5 | cut -c$s- | cut -c-4`             # slice of length 4
   GATE=`printf "%d" $((0x$gate % 32767 + 32768 ))`

   prot=`echo $d5 | cut -c$((s+4))`                   # next character
   PROT=`printf "%d" $((0x$prot % 2))`
   if [ $PROT -eq 0 ] ; then PROT='tcp' ; else PROT='udp' ; fi

   echo -n "$GATE/$PROT "
   echo > /dev/$PROT/$IP/$GATE &
   sleep 0.3
   kill $!

done

echo

# vim:tw=0

